<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    class="workflow-dialog"
  >
    <div class="dialog-content">
      <WorkflowConfig
        v-if="dialogVisible"
        :initial-config="initialConfig"
        :initial-step="initialStep"
        :initial-step-validation="initialStepValidation"
        ref="workflowConfigRef"
        @update:config="handleConfigUpdate"
        @update:step="handleStepUpdate"
        @update:step-validation="handleStepValidationUpdate"
        @export="handleExport"
      />
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ mode === 'add' ? '创建' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import WorkflowConfig from './workflowConfig.vue'
import type { WorkflowConfiguration } from './types'
import { saveWorkflow } from '/@/api/workflow'

interface Props {
  visible: boolean
  config?: WorkflowConfiguration | null
  mode: 'add' | 'edit' | 'copy'
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  config: null,
  mode: 'add'
})

const workflowConfigRef = ref(null)

const emit = defineEmits<Emits>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 弹窗标题
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'add':
      return '新增工作流配置'
    case 'edit':
      return '编辑工作流配置'
    case 'copy':
      return '复制工作流配置'
    default:
      return '工作流配置'
  }
})

// 保存状态
const saving = ref(false)

// 配置数据
const currentConfig = ref<WorkflowConfiguration | null>(null)
const currentStep = ref(0)
const currentStepValidation = ref<Record<number, boolean>>({})

// 初始化配置
const initialConfig = computed(() => {
  if (props.mode === 'add') {
    return null
  }
  return props.config
})

const initialStep = computed(() => {
  return props.mode === 'add' ? 0 : 0
})

const initialStepValidation = computed(() => {
  return props.mode === 'add' ? [false, false, true] : [true, true, true]
})

// 监听配置变化
watch(
  () => props.config,
  (newConfig) => {
    if (newConfig) {
      currentConfig.value = { ...newConfig }
    } else {
      currentConfig.value = null
    }
  },
  { immediate: true }
)

// 处理配置更新
const handleConfigUpdate = (config: WorkflowConfiguration) => {
  currentConfig.value = config
}

// 处理步骤更新
const handleStepUpdate = (step: number) => {
  currentStep.value = step
}

// 处理步骤验证更新
const handleStepValidationUpdate = (validation: Record<number, boolean>) => {
  currentStepValidation.value = validation
}

// 处理导出
const handleExport = (config: WorkflowConfiguration) => {
  // 导出功能可以在这里实现
  console.log('打印配置:', config)
}

// 检查是否可以保存
const canSave = computed(() => {
  if (!currentConfig.value) return false
  
  // 检查基本信息是否完整
  const { basicInfo } = currentConfig.value
  if (!basicInfo?.name?.trim()) return false
  
  // 可以添加更多验证逻辑
  return true
})

// 保存配置
const handleSave = async () => {
  // 检查组件引用是否存在
  if (!workflowConfigRef.value) {
    ElMessage.error('配置组件未加载完成，请稍后重试')
    return
  }
  
  // 调用config.vue中的validate函数
  if (!workflowConfigRef.value.validate()) {
    return
  }

  if (!canSave.value) {
    ElMessage.warning('请完善必填信息')
    return
  }
  
  if (!currentConfig.value) {
    ElMessage.error('配置数据不能为空')
    return
  }
  
  saving.value = true
  
  try {
    // TODO: 调用API保存配置
    console.log("原始数据: "+currentConfig)
    console.log("Json序列化: "+JSON.stringify(currentConfig.value))
    await saveWorkflow(currentConfig.value)

    ElMessage.success(
      props.mode === 'add' ? '创建成功' : 
      props.mode === 'copy' ? '复制成功' : '保存成功'
    )
    
    emit('success')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 取消操作
const handleCancel = async () => {
  // 检查是否有未保存的更改
  if (currentConfig.value && hasUnsavedChanges()) {
    try {
      await ElMessageBox.confirm(
        '当前有未保存的更改，确定要关闭吗？',
        '确认关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return // 用户取消关闭
    }
  }
  
  dialogVisible.value = false
}

// 检查是否有未保存的更改
const hasUnsavedChanges = (): boolean => {
  // 这里可以实现更复杂的变更检测逻辑
  // 暂时返回 false
  return false
}
</script>

<style scoped>
.workflow-dialog {
  :deep(.el-dialog) {
    margin-top: 5vh;
    margin-bottom: 5vh;
    height: 90vh;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-dialog__header) {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-dialog__footer) {
    padding: 16px 24px 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.dialog-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 确保内嵌的 config 组件能够正确显示 */
:deep(.workflow-designer) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.workflow-designer .content-container) {
  flex: 1;
  overflow: auto;
}

:deep(.workflow-designer .footer-actions) {
  display: none; /* 隐藏 config.vue 自带的底部按钮 */
}
</style>